<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card>
      <!-- 添加用户 -->
      <el-button type="primary" @click="addDialogVisible = true">
        添加角色</el-button
      >
      <el-dialog
        title="添加用户"
        :visible.sync="addDialogVisible"
        width="30%"
        @close="addDialogClosed"
      >
        <!-- 添加表单区 -->
        <el-form
          :rules="addFormRules"
          ref="addFormRef"
          :model="addForm"
          label-width="80px"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="addForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="addForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 角色列表 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <el-row
              v-for="(item1, index1) in scope.row.children"
              :class="[index1 === 0 ? '' : 'bdtop', ['vcenter']]"
              :key="item1.id"
            >
              <!-- 一级权限 -->
              <el-col :span="5">
                <el-tag @close="removeRightsById(scope.row, item1.id)" closable>
                  {{ item1.authName }}</el-tag
                >
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级权限和三级权限 -->

              <el-col :span="19">
                <el-row
                  v-for="(item2, index2) in item1.children"
                  :class="[index2 === 0 ? '' : 'bdtop', ['vcenter']]"
                  :key="item2.id"
                >
                  <!-- 二级 -->
                  <el-col :span="6">
                    <el-tag
                      @close="removeRightsById(scope.row, item2.id)"
                      closable
                      type="success"
                      >{{ item2.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级 -->
                  <el-col :span="18">
                    <el-tag
                      closable
                      type="warning"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      @close="removeRightsById(scope.row, item3.id)"
                      >{{ item3.authName }}</el-tag
                    >
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>

        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作" prop="level" width="300px">
          <template slot-scope="scope">
            <el-row>
              <el-button
                v-permission="[139]"
                @click="showEditDialog(scope.row.id)"
                type="primary"
                icon="el-icon-edit"
                size="mini"
                >编辑</el-button
              >
              <el-button
                v-permission="[130]"
                @click="showDelete(scope.row.id)"
                type="danger"
                icon="el-icon-delete"
                size="mini"
                >删除</el-button
              >
              <el-button
                v-permission="[134]"
                @click="showSetRightDialog(scope.row)"
                type="warning"
                icon="el-icon-setting"
                size="mini"
                >分配权限</el-button
              >
            </el-row>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 修改用户弹框 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%">
      <!-- 主体内容 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogClosed">取 消</el-button>
        <el-button type="primary" @click="eidtUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限对话框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="setRightDialogVisible"
      width="50%"
      @close="setRightDialogClose"
    >
      <!-- 树形控件 -->
      <el-tree
        show-checkbox
        node-key="id"
        default-expand-all
        :data="rightsList"
        :props="treeProps"
        :default-checked-keys="defkeys"
        ref="treeRef"
      ></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRightDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { mapState } from 'vuex'
export default {
  data() {
    return {
      // 当前即将分配权限的角色id
      roleId: '',
      // 默认选中的id值数组
      defkeys: [],
      // 分配权限对话框显示隐藏
      setRightDialogVisible: false,
      // 所有角色列表数据
      // rolesList: [],
      // 所有权限数据
      rightsList: [],
      // 修改对话框隐藏
      addDialogVisible: false,
      // 添加用户对象
      addForm: {
        roleDesc: '',
        roleName: '',
      },

      addFormRules: {
        roleName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '长度在 1 到 10 个字符',
            trigger: 'blur',
          },
        ],
        roleDesc: [
          { required: true, message: '请描述', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '长度在 1 到 10 个字符',
            trigger: 'blur',
          },
        ],
      },
      editDialogVisible: false,
      //编辑用户对象
      editForm: {
        roleId: 0,
        roleDesc: '',
        roleName: '',
      },
      editFormRules: {
        roleName: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '长度在 1 到 10 个字符',
            trigger: 'blur',
          },
        ],
        roleDesc: [
          { required: true, message: '请描述', trigger: 'blur' },
          {
            min: 1,
            max: 10,
            message: '长度在 1 到 10 个字符',
            trigger: 'blur',
          },
        ],
      },
      // 树形控件的属性绑定对象
      treeProps: {
        children: 'children',
        label: 'authName',
      },
    }
  },
  computed: {
    // 使用 mapState 辅助函数来映射 Vuex state 中的 rolesList
    ...mapState(['rolesList']),
  },
  created() {
    this.getRolesList()
  },
  methods: {
    async getRolesList() {
      this.$store.dispatch('getRolesList')
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
    },
    async addUser() {
      this.$refs.addFormRef.validate(async (valide) => {
        if (!valide) {
          return this.$message.error('请填写完整用户信息')
        }
        // 发送请求完成添加用户的操作
        const { data: res } = await this.$http.post('roles', this.addForm)
        if (res.meta.status !== 201) {
          //   console.log(res)
          return this.$message.error(res.meta.msg)
        }
        // 添加成功的提示
        this.$message.success('添加用户成功')
        // 关闭对话框
        this.addDialogVisible = false
        // 重新请求最新的数据
        this.getRolesList()
      })
    },
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('roles/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.msg)
      }
      // console.log(res)

      // 查询成功，将用户数据保存到editForm 中
      this.editForm = res.data
      // 显示弹框
      this.editDialogVisible = true
    },
    // 编辑确认
    eidtUser() {
      // 首先验证表单合法
      this.$refs.editFormRef.validate(async (valide) => {
        if (!valide) {
          return this.$message.error('请填写完整用户信息')
        }
        const { data: res } = await this.$http.put(
          'roles/' + this.editForm.roleId,
          { roleName: this.editForm.roleName, roleDesc: this.editForm.roleDesc }
        )
        if (res.meta.status !== 200)
          return this.$message.error('更新用户信息失败')
        // 关闭弹框
        this.editDialogVisible = false
        // 重新请求最新数据
        this.getRolesList()
        this.$message.success('更新用户信息成功')
      })
    },
    // 关闭修改用户弹窗时，清空表单字段
    editDialogClosed() {
      this.editDialogVisible = false
      this.$refs.editFormRef.resetFields()
    },
    async showDelete(id) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该用户, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)
      // console.log(confirmResult)
      // 点击取消删除
      if (confirmResult !== 'confirm') return this.$message.info('已取消删除')
      // 确认删除
      const { data: res } = await this.$http.delete('roles/' + id)
      // console.log(res)
      if (res.meta.status != 200) {
        return this.$message.error('不允许删除admin账户')
      }
      this.getRolesList()
      this.$message.success('删除成功')
    },
    // 传入参数：权限对象 需要删除的权限id
    async removeRightsById(role, rightId) {
      const confirmResult = await this.$confirm(
        '此操作将永久删除该权限, 是否继续?',
        '删除权限',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch((err) => err)

      if (confirmResult !== 'confirm') {
        return this.$message.info('取消了删除')
      }
      const { data: res } = await this.$http.delete(
        `roles/${role.id}/rights/${rightId}`
      )
      if (res.meta.status !== 200) {
        this.$message.error('删除权限失败！')
      }
      // 重新加载角色列表,这种会导致整个角色列表刷新，角色展开栏关闭
      // this.getRolesList()
      // 返回的数据包含了最新的权限数据
      role.children = res.data
      this.$message.success('删除权限成功')
    },
    // 分配权限对话框
    async showSetRightDialog(row) {
      this.roleId = row.id
      // 获取所有权限数据
      const { data: res } = await this.$http.get('rights/tree')
      // console.log(res)
      if (res.meta.status != 200) return this.$message.error('获取权限失败')
      this.rightsList = res.data
      // 递归获取3级节点id
      this.getLeafKey(row, this.defkeys)
      this.setRightDialogVisible = true
    },
    // 递归调用函数，获取三级节点的id
    getLeafKey(node, arr) {
      // 如果节点不存在children属性，说明是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }

      // 遍历node节点
      node.children.forEach((element) => {
        this.getLeafKey(element, arr)
      })
    },
    // 监听分配权限对话框的关闭事件
    setRightDialogClose() {
      this.defkeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ]
      // console.log(keys)
      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(
        `roles/${this.roleId}/rights`,
        { rids: idStr }
      )
      if (res.meta.status != 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList()
      this.setRightDialogVisible = false
    },
  },
}
</script>
<style lang="less" scoped>
.vcenter {
  display: flex;
  align-items: center;
}
</style>
